package com.intct.hbase.ddl.table;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

/**
 * @author gufg
 * @since 2025-08-06 09:46
 */
public class TruncateTable {
    public static void main(String[] args) throws IOException {
        // 创建HBase连接
        Connection connection = ConnectionFactory.createConnection();

        // 获取Admin实例
        Admin admin = connection.getAdmin();

        // 创建TableName实例
        TableName tableName = TableName.valueOf("intct83", "t5");

        try {
            // 判断存在
            if (admin.tableExists(tableName)) {
                // API中必须先禁用，才能执行truncate操作
                // 重复禁用表时，会报错。建议：先判断表是否已禁用
                if (!admin.isTableDisabled(tableName)) {
                    admin.disableTable(tableName);
                }
                // 清空表
                admin.truncateTable(tableName, false);
            } else {
                System.out.println("表不存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭
            if (admin != null){
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
